package com.it.data_queue;

import java.util.Iterator;

/**
 * @author: Coke
 * @DateTime: 2023/06/11/11:54
 * TODO
 **/
public class LinkedListQueue<E> implements Queue<E>, Iterable<E> {
    
    Node<E> head = new Node<>(null, null);
    Node<E> tail = head;
    
    int size; // 节点数
    
    int capacity = 10; // 容量
    
    public LinkedListQueue (int capacity) {
        this.capacity = capacity;
        tail.next = head;
    }
    
    public LinkedListQueue () {
        tail.next = head;
    }
    
    
    @Override
    public boolean offer (E value) {
        if (isFull()) {
            return false;
        }
        Node<E> newNode = new Node<>(value, head);
        tail.next = newNode;
        tail = newNode;
        size++;
        return true;
    }
    
    @Override
    public E pool () {
        if (isEmpty()) {
            return null;
        }
        Node<E> next = head.next;
        head.next = next.next;
        // 只有一个节点时
        if (next == tail) {
            tail = head;
        }
        size--;
        return next.val;
    }
    
    @Override
    public E peek () {
        if (isEmpty()) {
            return null;
        }
        return head.next.val;
    }
    
    @Override
    public boolean isEmpty () {
        return head == tail;
    }
    
    @Override
    public boolean isFull () {
        return size >= capacity;
    }
    
    @Override
    public Iterator<E> iterator () {
        return new Iterator<E>() {
            Node<E> p = head.next;
            
            @Override
            public boolean hasNext () {
                return p != head;
            }
            
            @Override
            public E next () {
                E val = p.val;
                p = p.next;
                return val;
            }
        };
    }
}
